package com.spider.moudle.writer;



import com.spider.moudle.api.Writer;
import com.spider.moudle.constant.Constant;
import com.spider.moudle.entity.Task;
import com.spider.moudle.entity.TaskType;
import com.spider.moudle.util.DateUtil;
import com.spider.moudle.util.ErrorLogUtil;

import java.io.File;
import java.io.IOException;
import java.util.Map;

/**
 * @author 夏茂轩
 * @package com.spider.silence.output
 * @Date 2017/6/21 9:46
 */
public class FileWriter implements Writer {

    @Override
    public boolean write(String path, String fileName, String content) throws Exception {
        throw new Exception("废弃方法，禁止使用");
    }

    @Override
    public boolean write(String path, String fileName, String content, Map<String, File> files) throws Exception {
        throw new Exception("废弃方法，禁止使用");
    }

    @Override
    public boolean write(String path, String fileName, String content, TaskType taskType) throws Exception {
        final boolean[] flag = {true};
        try {
            if(TaskType.SPEECH == taskType) {
                path = path.substring(14, path.length());
                path = path.replaceAll("_","//" ) + "//";
            } else if(TaskType.USER == taskType) {
                path = path + "//users" + "//";
            }
            String file_N = Constant.FILE_FOLDER + "//" + path;
            File file =new File(file_N);
            if(!file.exists()){
                file.mkdirs();
            }
            file = new File(file_N + fileName);
            java.io.FileWriter fw = new java.io.FileWriter(file);
            fw.write(content);
            fw.flush();
            fw.close();
            System.out.println("{method: 'file', type: '" + taskType + "', id:'" + path.replace("//", "_") + fileName + "', status:'success', nowTime:'" + DateUtil.getNowTimeString(DateUtil.yyyy_MM_dd_HH_mm_ss) + "'}");
        } catch (IOException e) {
            System.out.println("{method: 'file', type: '" + taskType + "', id:'" + path.replace("//", "_") + fileName + "', status:'error', nowTime:'" + DateUtil.getNowTimeString(DateUtil.yyyy_MM_dd_HH_mm_ss) + "'}");
            ErrorLogUtil.error(e.getMessage(), e);
            flag[0] = false;
        }
        return flag[0];
    }

    @Override
    public void write(String topic, Task task) throws Exception {
        throw new Exception("文件输出器不建议输出任务");
    }
}
